package com.wangliang.deepseek.window;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextArea;
import com.intellij.util.ui.JBUI;
import com.wangliang.deepseek.service.DeepSeekService;
import com.wangliang.deepseek.ui.ChatMessagePanel;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

@Slf4j
public class DeepSeekToolWindow {
    private final JPanel mainContent;
    private final JBTextArea inputArea;
    private final JBTextArea outputArea;
    private final Project project;
    private final DeepSeekService deepSeekService;

    // 添加新的成员变量
    private final JPanel messagesPanel;
    private final JScrollPane scrollPane;

    public DeepSeekToolWindow(Project project) {
        this.project = project;
        this.deepSeekService = new DeepSeekService();

        // 初始化消息面板
        this.messagesPanel = new JPanel();
        messagesPanel.setLayout(new BoxLayout(messagesPanel, BoxLayout.Y_AXIS));
        messagesPanel.setBackground(new Color(43, 43, 43));

        // 初始化滚动面板
        this.scrollPane = new JBScrollPane(messagesPanel);
        scrollPane.setBorder(JBUI.Borders.empty());
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);

        // 初始化输入区域
        this.inputArea = new JBTextArea();
        this.inputArea.setRows(5); // 增加输入框高度
        this.inputArea.setColumns(50);
        this.inputArea.setBackground(new Color(43, 45, 48)); // 更深的背景色
        this.inputArea.setForeground(new Color(187, 187, 187)); // 更柔和的文字颜色
        this.inputArea.setCaretColor(Color.WHITE); // 设置光标颜色
        this.inputArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14)); // 使用微软雅黑
        this.inputArea.setBorder(JBUI.Borders.empty(10));
        this.inputArea.setLineWrap(true); // 自动换行
        this.inputArea.setWrapStyleWord(true); // 按单词换行

        // 添加回车发送快捷键
        inputArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown()) {
                    e.consume();
                    sendQuery();
                }
            }
        });

        // 添加提示文本
        inputArea.setText("按 Ctrl+Enter 发送消息");
        inputArea.setForeground(new Color(128, 128, 128));
        inputArea.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (inputArea.getText().equals("按 Ctrl+Enter 发送消息")) {
                    inputArea.setText("");
                    inputArea.setForeground(new Color(187, 187, 187));
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (inputArea.getText().isEmpty()) {
                    inputArea.setText("按 Ctrl+Enter 发送消息");
                    inputArea.setForeground(new Color(128, 128, 128));
                }
            }
        });

        // 初始化输出区域
        this.outputArea = new JBTextArea();
        this.outputArea.setEditable(false);
        this.outputArea.setBackground(new Color(43, 45, 48));
        this.outputArea.setForeground(new Color(187, 187, 187));
        this.outputArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        this.outputArea.setBorder(JBUI.Borders.empty(10));
        this.outputArea.setLineWrap(true);
        this.outputArea.setWrapStyleWord(true);

        // 初始化主面板
        this.mainContent = new JPanel(new BorderLayout(0, 10));
        this.mainContent.setBackground(new Color(43, 43, 43));
        this.mainContent.setBorder(JBUI.Borders.empty(10));

        // 创建顶部欢迎区域
        JPanel welcomePanel = createWelcomePanel();
        mainContent.add(welcomePanel, BorderLayout.NORTH);

        // 添加消息区域
        mainContent.add(scrollPane, BorderLayout.CENTER);

        // 创建底部输入区域
        JPanel inputPanel = createInputPanel();
        mainContent.add(inputPanel, BorderLayout.SOUTH);
    }

    private JPanel createWelcomePanel() {
        // 创建一个半透明的欢迎面板
        JPanel welcomePanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建渐变背景
                GradientPaint gradient = new GradientPaint(
                        0, 0, new Color(49, 51, 53, 200),
                        0, getHeight(), new Color(43, 43, 43, 200));
                g2.setPaint(gradient);
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);

                // 添加细微的边框
                g2.setColor(new Color(73, 76, 78, 150));
                g2.setStroke(new BasicStroke(1f));
                g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 10, 10);

                g2.dispose();
            }
        };

        welcomePanel.setLayout(new BorderLayout(0, 5));
        welcomePanel.setOpaque(false);
        welcomePanel.setBorder(new EmptyBorder(10, 15, 10, 15));

        // 创建标题面板
        JPanel headerPanel = new JPanel(new BorderLayout(10, 0));
        headerPanel.setOpaque(false);

        // 添加图标
        JLabel iconLabel = new JLabel(AllIcons.General.Modified);
        iconLabel.setBorder(JBUI.Borders.empty(0, 0, 0, 5));
        headerPanel.add(iconLabel, BorderLayout.WEST);

        // 添加标题和副标题
        JPanel textPanel = new JPanel(new GridLayout(2, 1, 0, 2));
        textPanel.setOpaque(false);

        JLabel titleLabel = new JLabel("DeepSeek AI 助手");
        titleLabel.setForeground(new Color(209, 209, 209));
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        textPanel.add(titleLabel);

        JLabel subtitleLabel = new JLabel("您的智能编程助手");
        subtitleLabel.setForeground(new Color(169, 169, 169));
        subtitleLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        textPanel.add(subtitleLabel);

        headerPanel.add(textPanel, BorderLayout.CENTER);
        welcomePanel.add(headerPanel, BorderLayout.CENTER);

        // 添加快捷键提示
        JPanel shortcutPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        shortcutPanel.setOpaque(false);

        // 创建带有图标的快捷键提示
        JLabel shortcutLabel = new JLabel(AllIcons.Actions.Execute);
        shortcutLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        shortcutLabel.setForeground(new Color(169, 169, 169));
        shortcutLabel.setText(" Ctrl+Enter 发送消息  ");
        shortcutPanel.add(shortcutLabel);

        JLabel separator = new JLabel("•");
        separator.setForeground(new Color(169, 169, 169));
        separator.setBorder(JBUI.Borders.empty(0, 5));
        shortcutPanel.add(separator);

        JLabel suggestLabel = new JLabel(AllIcons.Actions.QuickfixBulb);
        suggestLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        suggestLabel.setForeground(new Color(169, 169, 169));
        suggestLabel.setText(" Ctrl+Space 获取建议");
        shortcutPanel.add(suggestLabel);

        welcomePanel.add(shortcutPanel, BorderLayout.SOUTH);

        // 创建一个容器面板来添加上下边距
        JPanel containerPanel = new JPanel(new BorderLayout());
        containerPanel.setOpaque(false);
        containerPanel.setPreferredSize(new Dimension(-1, 80)); // 设置固定高度
        containerPanel.setBorder(JBUI.Borders.empty(5, 0));
        containerPanel.add(welcomePanel, BorderLayout.CENTER);

        return containerPanel;
    }

    private JPanel createInputPanel() {
        JPanel inputPanel = new JPanel(new BorderLayout(0, 10));
        inputPanel.setBackground(new Color(43, 43, 43));
        inputPanel.setBorder(JBUI.Borders.empty(10));

        // 创建一个带有圆角和边框的面板来包装输入区域
        JPanel inputWrapper = new JPanel(new BorderLayout());
        inputWrapper.setBackground(new Color(43, 45, 48));
        inputWrapper.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(60, 63, 65)),
                BorderFactory.createEmptyBorder(1, 1, 1, 1)));

        JBScrollPane inputScrollPane = new JBScrollPane(inputArea);
        inputScrollPane.setBorder(JBUI.Borders.empty());
        inputScrollPane.setBackground(new Color(43, 45, 48));
        inputWrapper.add(inputScrollPane);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
        buttonPanel.setBackground(new Color(43, 43, 43));

        JButton sendButton = createStyledButton("发送");
        sendButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        sendButton.addActionListener(e -> sendQuery());
        buttonPanel.add(sendButton);

        inputPanel.add(inputWrapper, BorderLayout.CENTER);
        inputPanel.add(buttonPanel, BorderLayout.SOUTH);

        return inputPanel;
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setBackground(new Color(75, 110, 175)); // 更柔和的蓝色
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(75, 110, 175)),
                BorderFactory.createEmptyBorder(8, 20, 8, 20))); // 增加按钮内边距
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(90, 130, 200));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(75, 110, 175));
            }
        });

        return button;
    }

    private void sendQuery() {
        String query = inputArea.getText();
        if (query.trim().isEmpty() || query.equals("按 Ctrl+Enter 发送消息")) {
            return;
        }

        // 添加用户问题到输出区域
        appendMessage("User", query);

        // 显示AI正在思考
        appendMessage("Assistant", "思考中...");

        // 清空输入框并重置状态
        inputArea.setText("");
        inputArea.setForeground(new Color(187, 187, 187));

        StringBuilder currentResponse = new StringBuilder();

        deepSeekService.sendStreamQuery(
                query,
                // 处理流式响应
                content -> SwingUtilities.invokeLater(() -> {
                    if (currentResponse.length() == 0) {
                        // 移除"思考中..."消息
                        removeThinkingMessage();
                    }
                    currentResponse.append(content);
                    updateLatestAssistantMessage(currentResponse.toString());
                }),
                // 处理错误
                error -> SwingUtilities.invokeLater(() -> {
                    log.error("发送查询时出错", error);
                    removeThinkingMessage();
                    appendMessage("System", "错误: " + error.getMessage());
                }));
    }

    private void removeThinkingMessage() {
        Component[] components = messagesPanel.getComponents();
        if (components.length > 0) {
            messagesPanel.remove(components.length - 1);
            messagesPanel.revalidate();
            messagesPanel.repaint();
        }
    }

    private void updateLatestAssistantMessage(String content) {
        ChatMessagePanel messagePanel = new ChatMessagePanel("Assistant", content);

        Component[] components = messagesPanel.getComponents();
        if (components.length > 0 && components[components.length - 1] instanceof ChatMessagePanel) {
            messagesPanel.remove(components.length - 1);
        }

        messagesPanel.add(messagePanel);
        messagesPanel.revalidate();
        messagesPanel.repaint();

        // 滚动到底部
        JScrollBar vertical = scrollPane.getVerticalScrollBar();
        vertical.setValue(vertical.getMaximum());
    }

    private void appendMessage(String role, String message) {
        SwingUtilities.invokeLater(() -> {
            ChatMessagePanel messagePanel = new ChatMessagePanel(role, message);

            // 添加新消息
            messagesPanel.add(messagePanel);
            messagesPanel.revalidate();
            messagesPanel.repaint();

            // 滚动到底部
            SwingUtilities.invokeLater(() -> {
                JScrollBar vertical = scrollPane.getVerticalScrollBar();
                vertical.setValue(vertical.getMaximum());
            });
        });
    }

    private String formatResponse(String response) {
        // 检查是否包含代码块
        if (response.contains("```")) {
            StringBuilder formatted = new StringBuilder();
            String[] lines = response.split("\n");
            boolean inCodeBlock = false;

            for (String line : lines) {
                if (line.startsWith("```")) {
                    inCodeBlock = !inCodeBlock;
                    // 如果是代码块开始，添加语言标识
                    if (inCodeBlock && line.length() > 3) {
                        formatted.append("```").append(line.substring(3)).append("\n");
                    } else {
                        formatted.append("```\n");
                    }
                } else {
                    formatted.append(line).append("\n");
                }
            }
            return formatted.toString();
        }
        return response;
    }

    public JComponent getContent() {
        return mainContent;
    }
}